﻿$(document).ready(function(){
	/* Hack layout here. If we comment out two below lines and click tab 'Bộ sưu tập', 
	the main menu displays wrongly unexpectedly. 
	I spent whole day to try to fix this bug the elegant way but I did unsuccessfully.
	I don't know why but I think the designer of this layout did something wrong with CSS.
	*/
	$('#mainMenuWrapper').attr('style', 'padding: 0px 5px 0px 5px;');
	$('#logo').attr('style', 'padding: 5px 5px 2.6px 5px;');
	
	$('#mediaTabContent').hide();
	
	// general-purposed variables
	var timeOutTime = 5000;	
	var selectPriv = 1;
	var insertPriv = 1;
	var updatePriv = 1;
	var deletePriv = 1;
	var selectedAlbumID = -1;
	var selectedAlbumType = 'photo';
	
	// album tab content variables
	var numberOfAlbums = 15;
	var pageOfAlbum = 0;
	
	// media tab content variables
	var numberOfMedia = 15;
	var pageOfMedia = 0;
	
	// init controls (these must be done FIRST!)
	initControls();
	initMediaControls();
	
	// this is synchronous function, so it must runs after initControl
	getPrivs();	
	
	// album tab content
	shouldCreateNewButton();
	shouldListAlbum();
	
	// media tab content
	shouldCreateMediaNewButton();
	
	//================ Quick tips ==================//
	function quickTip()
	{
		$(".editAlbum").qtip({
			content: "Sửa album",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
		$(".removeAlbum").qtip({
			content: "Xóa album",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
	} // end quickTip function	
	
	//================ Event helpers ==================//
	function newAlbum()
	{		
		$("#newAlbumErrorRow").hide();
		$("#newAlbumDialog").dialog("open");	
		$('#newAlbumName').focus();		
	}
	
	function editAlbum(albumID)
	{
		if (albumID > 0)
		{		
			$.ajax({
				type: 'GET',
				url: '/xalbum/get-info', 
				data: {id: albumID}, 
				beforeSend: function() {
					blockUI();
				}, // end beforeSend function
				success: function(data){
					unblockUI();
					var returnData = $.parseJSON(data);
					if (returnData.code == 0)
					{
						$("#editAlbumErrorRow").hide();
						$("#editAlbumType").val(returnData.data.album_type);					
						$("#editAlbumID").val(returnData.data.id);
						$("#editAlbumName").val(returnData.data.name);						
						$("#editAlbumDescription").val(returnData.data.description);					
						$("#editAlbumDialog").dialog("open");
						$('#editAlbumName').focus();
					}
				}, // end success function				
			}); // end $.ajax call
		}
	}
	
	function removeAlbum(albumID)
	{
		if (albumID > 0)
		{
			$("#removeShowAlbumID").html(albumID);
			$("#removeAlbumID").val(albumID);
			$("#removeAlbumDialog").dialog("open");
		}
	}
	
	function newMedia()
	{		
		$("#newMediaErrorRow").hide();
		$("#newMediaDialog").dialog("open");				
	}
		
	function editMedia(mediaID)
	{
		if (mediaID > 0)
		{		
			$.ajax({
				type: 'GET',
				url: '/xmedia/get-info', 
				data: {id: mediaID, mediaType: selectedAlbumType}, 
				beforeSend: function() {
					blockUI();
				}, // end beforeSend function
				success: function(data){
					unblockUI();
					var returnData = $.parseJSON(data);
					if (returnData.code == 0)
					{
						$("#editMediaErrorRow").hide();						
						$("#editMediaID").val(returnData.data.id);
						$("#editMediaDescription").val(returnData.data.description);					
						$("#editMediaDialog").dialog("open");
						$('#editMediaDescription').focus();
					}
				}, // end success function				
			}); // end $.ajax call
		}	
	}
	
	function removeMedia(mediaID)
	{
		if (mediaID > 0)
		{
			$("#removeShowMediaID").html(mediaID);
			$("#removeMediaID").val(mediaID);
			$("#removeMediaDialog").dialog("open");
		}	
	}
		
	//================ Helpers ==================//
	function loadAlbum()
	{
		$.ajax({
			type: "GET",
			url: "/xalbum/list", 
			data: {albumType: selectedAlbumType, from: pageOfAlbum * numberOfAlbums, numberOfAlbums: numberOfAlbums},
			timeout: timeOutTime,
			beforeSend: function() {
				blockUI();
			}, // end beforeSend function,			
			success: function(data){
				unblockUI();
				var returnData = $.parseJSON(data);
				$('#listAlbumTable tbody').remove();
				var albumTableHTML = '<tbody>';
				for (var i = 0; i < returnData.data.length; i++)
				{
					albumTableHTML += "<tr>";
					albumTableHTML += '<td>' + returnData.data[i].id + "</td>";
					
					if(returnData.data[i].thumbnail_path != '') {
						albumTableHTML += '<td><img src="' + returnData.data[i].thumbnail_path + '" alt="' + returnData.data[i].thumbnail_path + '"/></td>';							
					} else {
						albumTableHTML += '<td>Không có ảnh đại diện</td>';							
					}
					
					albumTableHTML += '<td class="albumNameTd">' + returnData.data[i].name + "</td>";
					albumTableHTML += '<td>' + returnData.data[i].description + "</td>";
					albumTableHTML += '<td>' + returnData.data[i].create_date + "</td>";							
					
					if(updatePriv == 0 && deletePriv == 0) {
						albumTableHTML += '<td>Không có</td>';
					} else {
						albumTableHTML += 
						'<td>' + 
						(updatePriv ? '<a id="e' + returnData.data[i].id + '" href="#" class="editAlbum">Sửa</a>' : '') + 
						(updatePriv && deletePriv ? ' | ' : '') +
						(deletePriv ? '<a id="r' + returnData.data[i].id + '" href="#" class="removeAlbum">Xóa</a>' : '') + 
						'</td>';
					}

					albumTableHTML += '<td><a href="#" class="manageMedia" id="m' + returnData.data[i].id + '">' + $('#listAlbumType option:selected').text() + '</a></td>';
					albumTableHTML += '</tr>';
				}
				albumTableHTML += '</tbody>';
				$('#listAlbumTable').append(albumTableHTML);
				
				// Edit album event handler
				$(".editAlbum").click(function(){
					var albumID = $(this).attr("id").substr(1);						
					editAlbum(albumID);
					return false;
				});
				// Remove album event handler
				$(".removeAlbum").click(function(){
					var albumID = $(this).attr("id").substr(1);
					removeAlbum(albumID);
					return false;
				});
				
				// init quick tips for edit and remove links
				quickTip();
				
				$(".manageMedia").click(function(){	
					var manageMediaLink = $(this);
					$('#tab_content').slideUp(function() {						
						selectedAlbumID = manageMediaLink.attr('id').substr(1);					
						var albumName = manageMediaLink.parent('td').parent('tr').find('.albumNameTd').text();						
						showMediaTabContent(albumName);					
					});
						
				});
			}, // end success function			
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {					
					loadAlbum();
				}
			}
		}); // end $.ajax function
	}
	
	function loadMedia()
	{
		$.ajax({
			type: 'GET',
			url: '/xmedia/list-media',
			data: {albumID: selectedAlbumID, from: pageOfMedia * numberOfMedia, numberOfMedia: numberOfMedia},
			timeout: timeOutTime,
			beforeSend: function() {
				blockUI();
			}, // end beforeSend function,	
			success: function(data) {
				unblockUI();
				var returnData = $.parseJSON(data);
				$('#listMediaTable tbody').remove();
				
				var mediaTableHTML = '<tbody>';				
				for (var i = 0; i < returnData.data.length; i++)
				{
					mediaTableHTML += "<tr>";
					mediaTableHTML += '<td>' + returnData.data[i].id + "</td>";
					
					if(selectedAlbumType == 'photo') {
						if(returnData.data[i].thumbnail_path != '' || returnData.data[i].path != '') {
							var thumbnailPath = returnData.data[i].thumbnail_path;
							var path = returnData.data[i].path;
							mediaTableHTML += '<td><a href="' + path + '">' + 
											  '<img class="photoThumbnail" title="' +
											  path.substring(path.lastIndexOf('/') + 1) + 
											  '" src="' + thumbnailPath + '" alt="' + 
											  thumbnailPath.substring(thumbnailPath.lastIndexOf('/') + 1)
											  + '"/>' + 
											  '</a></td>';
						} else {
							mediaTableHTML += '<td>Không tìm thấy file</td>';							
						}
					} else {
						if(returnData.data[i].path != '') {					
							var path = returnData.data[i].path;
							mediaTableHTML += '<td><a href="' + path + '">' + 
											  '<img class="videoThumbnail" title="' + 
											  path.substring(path.lastIndexOf('/') + 1) + 
											  '" src="' + path + '" alt="' + 
											  path.substring(path.lastIndexOf('/') + 1)
											  + '"/>' + 
											  '</a></td>';
						} else {
							mediaTableHTML += '<td>Không tìm thấy file</td>';							
						}
					}
					

										
					mediaTableHTML += '<td>' + returnData.data[i].description + "</td>";
					mediaTableHTML += '<td>' + returnData.data[i].upload_date + "</td>";						
					
					if(updatePriv == 0 && deletePriv == 0) {
						mediaTableHTML += '<td>Không có</td>';
					} else {
						mediaTableHTML += 
						'<td>' + 
						(updatePriv ? '<a id="e' + returnData.data[i].id + '" href="#" class="editMedia">Sửa</a>' : '') + 
						(updatePriv && deletePriv ? ' | ' : '') +
						(deletePriv ? '<a id="r' + returnData.data[i].id + '" href="#" class="removeMedia">Xóa</a>' : '') + 
						'</td>';
					}	
					mediaTableHTML += '</tr>';
				}		
				mediaTableHTML += '</tbody>';
				$('#listMediaTable').append(mediaTableHTML);
				
				// Edit media event handler
				$(".editMedia").click(function(){
					var mediaID = $(this).attr("id").substr(1);						
					editMedia(mediaID);
					return false;
				});
				// Remove media event handler
				$(".removeMedia").click(function(){
					var mediaID = $(this).attr("id").substr(1);
					removeMedia(mediaID);
					return false;
				});
				
				// add photo effects
				addPhotoEffects();
			}, // end successs function
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {					
					loadMedia();
				}
			}
		});
	}
	
	function shouldCreateNewButton()
	{
		$('#newAlbumButtonWrapper').remove();		
		if(insertPriv) {
			var newButtonHTML = '<span id="newAlbumButtonWrapper" style="padding: 0 0 5px 0;"><input id="newAlbumButton" type="button" value="Thêm mới" /></span>';						
			
			// add it to tab content
			$('#albumTopWrapper').append(newButtonHTML);			
			
			// add UI
			$('#newAlbumButton').button();
			
			// add new event handler
			$("#newAlbumButton").click(function(){
				newAlbum();		
			});
		}
	} // end shouldCreateNewButton function
	
	// when select_priv is true, loadAlbumType select and listAlbumTableWrapper will show
	function shouldListAlbum()
	{
		if(selectPriv) {
			$('#listAlbumTypeSelectWrapper').show();
			$('#listAlbumTableWrapper').show();
			loadAlbum();
		} else {
			$('#albumSelectPrivReport').show();
		}
		
		// fix bug 'padding' of 'albumTopWrapper'
		if(insertPriv == 0 && selectPriv == 0) {
			$('#albumTopWrapper').remove();
		}
	} // end shouldListAlbum functions
	
	function shouldCreateMediaNewButton()
	{
		$('#newMediaButtonWrapper').remove();		
		if(insertPriv) {
			var newButtonHTML = '<span id="newMediaButtonWrapper" style="padding: 0 0 5px 0;"><input id="newMediaButton" type="button" value="Thêm mới" /></span>';
			
			// add it to tab content
			$('#mediaTopButtonWrapper').prepend(newButtonHTML);			
			
			// add UI
			$('#newMediaButton').button();
			
			// add new event handler
			$("#newMediaButton").click(function(){				
				newMedia();		
			});
		}
	}
	
	// when select_priv is true, listMediaTableWrapper will show
	function shouldListMedia()
	{
		if(selectPriv) {				
			$('#listMediaTableWrapper').show();
			loadMedia();
		} else {
			$('#mediaSelectPrivReport').show();
		}
		
		// fix bug 'padding' of 'mediaTopWrapper'
		if(insertPriv == 0 && selectPriv == 0) {
			$('#mediaTopWrapper').remove();
		}
	} // end shouldListMedia functions
	
	function showMediaTabContent(albumName)
	{	
		// show media tab content
		$('#mediaTabContent').fadeIn();

		$('#albumNameSpan').html(albumName);

		// list media on the fly because it cannot be listed at the beginning.
		shouldListMedia();
	}
	
	function addPhotoEffects()
	{
		// add hover effect
		$('#listMediaTable img').hover(function(){
			$(this).css('opacity', 1);
		},
		function(){
			$(this).css('opacity', 0.8);
		});	
	
		// add yoxview effect
		$("#listMediaTable").yoxview();
	}

	function getPrivs()
	{
		// get privileges (placeholder)
	}
		
	///////// deprecated ////////
	function addAlbumUploadEventHandler()
	{
		$('#newAlbumUpload_queue .cancel a').bind('click', function(){
			var fileName = $('#newAlbumFilename').val();
			deleteTempFile(fileName);
			// var id = $('.uploadifyQueueItem').first().attr('id');
			// alert('#' + id);
			// $('newAlbumUpload').uploadifyCancel('#' + id);			
		});
	}
	
	///////// deprecated ////////
	function deleteTempFile(fileName)
	{
		var data = 'fileName=' + fileName;
		$.ajax({
			type: 'POST',
			url: '/xalbum/delete-temp-file',
			data: data,
			success: function(data) {
				var returnData = $.parseJSON(data);				
			},
			error: function(jqXHR, textStatus, errorThrown) {
				alert('Lỗi');
			}
		});
	}
	
	function blockUI()
	{
		$.blockUI({ message: '<h2><img src="/x/images/busy.gif" /> Đang xử lý...</h2>' });
	}
	
	function unblockUI()
	{
		$.unblockUI();
	}
	
	//================ Init functions ==================//
	function initControls()
	{
		initAlbumTypeSelect();
		initNewAlbumDialog();
		initEditAlbumDialog();
		initRemoveAlbumDialog();
		initNewAlbumUpload();
		initEditAlbumUpload();	
	}
	
	function initAlbumTypeSelect()
	{
		$('#listAlbumType').change(function(){	
			selectedAlbumType = $(this).val();
			loadAlbum();
			
			changeMediaUploadType(selectedAlbumType);
		}).val('photo');
	}
	
	function initNewAlbumDialog()
	{
		$("#newAlbumDialog").dialog({
			autoOpen: false,
			width: 350,
			resizable: false,
			buttons: 
			[
				{
					id: 'newAlbumSubmit',
					text: "Thêm",
					click: function(){		
						$("#newAlbumErrorRow").hide();
						$.ajax({
							type: 'POST',
							url: '/xalbum/add', 
							data: $('#newAlbumForm').serialize(), 
							beforeSend: function() {
								blockUI();
							}, // end beforeSend function
							success: function(data){	
								unblockUI();				
								var returnData = $.parseJSON(data);					
								if (returnData.code == 0)
								{		
									loadAlbum();
									$('#newAlbumDialog').dialog("close");					
								}
								else
								{						
									$("#newAlbumErrorRow").show();
									$("#newAlbumErrorMessage").html(returnData.data);
								}
							} // end success function					
						}); // end $.ajax call
						// if not successful, report errors
						return false;
					}
				},
				{
					text: "Đóng",
					click: function(){
						$(this).dialog("close");
					}
				}
			
			],
			close: function(event, ui)
			{	
				// remove old album cover file name tr
				$('#newAlbumCoverTr').remove();
			
				$('#newAlbumType').val('photo');
				$('#newAlbumName').val('');
				$("#newAlbumFilename").val("");
				$('#newAlbumDescription').val('');
			},
		});
	}
	
	function initEditAlbumDialog()
	{
		$("#editAlbumDialog").dialog({
			autoOpen: false,
			width: 350,
			resizable: false,
			buttons: 
			[
				{
					id: 'editAlbumSubmit',
					text: "Cập nhật",
					click: function(){
						$("#editAlbumErrorRow").hide();
						$.ajax({
							type: 'POST',
							url: '/xalbum/edit', 
							data: $('#editAlbumForm').serialize(), 
							beforeSend: function() {
								blockUI();
							}, // end beforeSend function
							success: function(data){
								unblockUI();
								var returnData = $.parseJSON(data);
								if (returnData.code == 0)
								{				
									loadAlbum();
									$('#editAlbumDialog').dialog("close");
								}
								else
								{
									$("#editAlbumErrorRow").show();
									$("#editAlbumErrorMessage").html(returnData.data);
								}
							} // end success function
						}); // end $.ajax call
						// if not successful, report errors
						return false;
					}
				},
				{
					text: "Đóng",
					click: function(){
						$(this).dialog("close");
					}
				}				
			],
			close: function(event, ui)
			{
				// remove old album cover file name tr
				$('#editAlbumCoverTr').remove();
				
				$('#editAlbumType').val('photo');
				$('#editAlbumName').val('');
				$("#editAlbumFilename").val("");
				$('#editAlbumDescription').val('');				
			}
		});
	}
	
	function initRemoveAlbumDialog()
	{
		$("#removeAlbumDialog").dialog({
			autoOpen: false,
			width: 220,
			resizable: false,
			buttons: {
				"Xóa": function(){
					$.ajax({
						type: 'POST',
						url: '/xalbum/remove', 
						data: $("#removeAlbumForm").serialize(),
						beforeSend: function() {
							blockUI();
						}, // end beforeSend function
						success: function(data){
							unblockUI();
							var returnData = $.parseJSON(data);
							if (returnData.code == 0)
							{
								loadAlbum();
								$('#removeAlbumDialog').dialog("close");
							}
						}, // end success function
					}); // end $.ajax call
					// if not successful, report errors
					$(this).dialog("close");
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			}
		});
	}
	
	function initNewAlbumUpload()
	{
		$("#newAlbumUpload").uploadify({
			"swf": "/x/uploadify/uploadify.swf",
			"uploader": "/x/uploadify/uploadify.php",
			//"buttonText": "+++",	
			'buttonClass': 'uploadButton',
			"cancelImage": "/x/uploadify/uploadify-cancel.png",
			'buttonImage': '/x/images/upload.gif',
			"checkExisting": "/x/uploadify/uploadify-check-exists.php",
			"auto" : true,		
			"fileTypeExts": "*.jpg;*.gif;*.png",
			"fileTypeDesc": "Image files",
			"height": 21,
			"width": 21,
			"removeCompleted": true,
			'removeTimeout': 0,
			'onSelect': function(file) {
				// remove old album cover file name tr
				$('#newAlbumCoverTr').remove();
				$('#newAlbumSubmit').attr('disabled', true);
			},
			"onUploadSuccess": function(file, data, response){
				$('#newAlbumSubmit').attr('disabled', false);
				var fileName = file.name;
				if (fileName == '')
				{
					$("#newAlbumErrorRow").show();
					$("#newAlbumErrorMessage").html(fileName);
					$("#newAlbumFilename").val('');			
				}
				else
				{
					$("#newAlbumErrorRow").hide();
					$("#newAlbumErrorMessage").html("");
					$("#newAlbumFilename").val(fileName);
				}
			},
			'onUploadComplete': function(file) {
				// add new album cover file name tr
				var fileName = $('#newAlbumFilename').val();
				
				// truncate if file name is too long
				if(fileName.length > 15)
					fileName = fileName.substring(0, 15) + '...';
				$('<tr id="newAlbumCoverTr">' + '<td></td><td>' + fileName + '</td>' + '</tr>').insertAfter('#newAlbumUploadTr').fadeIn();										
			}
		});	
	}
	
	function initEditAlbumUpload()
	{
		$("#editAlbumUpload").uploadify({
			"swf": "/x/uploadify/uploadify.swf",
			"uploader": "/x/uploadify/uploadify.php",
			"buttonText": "+++",
			'buttonClass': 'uploadButton',
			"cancelImage": "/x/uploadify/uploadify-cancel.png",
			'buttonImage': '/x/images/upload.gif',
			"checkExisting": "/x/uploadify/uploadify-check-exists.php",
			"auto" : true,
			"fileTypeExts": "*.jpg;*.gif;*.png",
			"fileTypeDesc": "Image files",
			"height": 21,
			"width": 21,
			"removeCompleted": true,
			'removeTimeout': 0,
			'onSelect': function(file) {
				// remove old album cover file name tr
				$('#editAlbumCoverTr').remove();
				$('#editAlbumSubmit').attr('disabled', true);
			},
			"onUploadSuccess": function(file, data, response){
				$('#editAlbumSubmit').attr('disabled', false);
				var fileName = file.name;
				if (fileName == '')
				{
					$("#editAlbumErrorRow").show();
					$("#editAlbumErrorMessage").html(fileName);
					$("#editAlbumFilename").val('');			
				}
				else
				{
					$("#editAlbumErrorRow").hide();
					$("#editAlbumErrorMessage").html("");
					$("#editAlbumFilename").val(fileName);
				}
			},
			'onUploadComplete': function(file) {
				// add new album cover file name tr
				var fileName = $('#editAlbumFilename').val();
				
				// truncate if file name is too long
				if(fileName.length > 15)
					fileName = fileName.substring(0, 15) + '...';
				$('<tr id="editAlbumCoverTr">' + '<td></td><td>' + fileName + '</td>' + '</tr>').insertAfter('#editAlbumUploadTr').fadeIn();										
			}
		});
	}
	
	function initBackButton()
	{
		$('#backButton').button();
		$('#backButton').click(function(){
			$('#mediaTabContent').fadeOut(function(){
				$('#tab_content').slideDown();
				
				// Remove listMediaTable body (this is optional, but it makes sliding up more effective).
				$('#listMediaTable tbody').remove();
			});			
		});
	}
	
	/////// Media tab content /////
	function initMediaControls()
	{
		initBackButton();
		initNewMediaDialog();
		initEditMediaDialog();
		initRemoveMediaDialog();
		initNewPhotoUpload();
		initNewVideoUpload();
	}
	
	function initNewMediaDialog()
	{
		$("#newMediaDialog").dialog({
			autoOpen: false,
			width: 350,
			resizable: false,
			buttons: 
			[
				{
					id: 'newMediaSubmit',
					text: 'Thêm',
					click: function(){
						$("#newMediaErrorRow").hide();
						var postData = $('#newMediaForm').serialize() + '&albumID=' + selectedAlbumID + '&mediaType=' + selectedAlbumType;
						$.ajax({
							type: 'POST',
							url: '/xmedia/add', 
							data: postData, 
							beforeSend: function() {
								blockUI();
							}, // end beforeSend function
							success: function(data){	
								unblockUI();				
								var returnData = $.parseJSON(data);					
								if (returnData.code == 0)
								{
									loadMedia();
									$('#newMediaDialog').dialog("close");					
								}
								else
								{	
									$("#newMediaErrorRow").show();
									$("#newMediaErrorMessage").html(returnData.data);
								}
							} // end success function					
						}); // end $.ajax call
						// if not successful, report errors
						return false;
					}
				},
				{
					text: 'Đóng',
					click: function(){
						$(this).dialog("close");
					}
				}
			],
			close: function(event, ui)
			{
				// remove old media file name tr
				$('.newMediaNameTr').remove();
				
				$("#newMediaFilename").val('');
				$('#newMediaDescription').val('');
			},
		});	
	}
	
	function initEditMediaDialog()
	{
		$("#editMediaDialog").dialog({
			autoOpen: false,
			width: 300,
			resizable: false,
			buttons: {
				"Cập nhật": function(){
					$("#editMediaErrorRow").hide();
					var postData = $('#editMediaForm').serialize() + '&mediaType=' + selectedAlbumType;
					$.ajax({
						type: 'POST',
						url: '/xmedia/edit', 
						data: postData, 
						beforeSend: function() {
							blockUI();
						}, // end beforeSend function
						success: function(data){
							unblockUI();
							var returnData = $.parseJSON(data);
							if (returnData.code == 0)
							{				
								loadMedia();
								$('#editMediaDialog').dialog("close");
							}
							else
							{
								$("#editMediaErrorRow").show();
								$("#editMediaErrorMessage").html(returnData.data);
							}
						} // end success function
					}); // end $.ajax call
					// if not successful, report errors
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$("#editMediaFilename").val("");
				$('#editMediaDescription').val('');				
			}
		});	
	}
	
	function initRemoveMediaDialog()
	{
		$("#removeMediaDialog").dialog({
			autoOpen: false,
			width: 220,
			resizable: false,
			buttons: {
				"Xóa": function(){
					$.ajax({
						type: 'POST',
						url: '/xmedia/remove', 
						data: $("#removeMediaForm").serialize() + '&mediaType=' + selectedAlbumType,
						beforeSend: function() {
							blockUI();
						}, // end beforeSend function
						success: function(data){
							unblockUI();
							var returnData = $.parseJSON(data);
							if (returnData.code == 0)
							{
								loadMedia();
								$('#removeMediaDialog').dialog("close");
							}
						}, // end success function
					}); // end $.ajax call
					// if not successful, report errors
					$(this).dialog("close");
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			}
		});
	}
	
	function initNewPhotoUpload()
	{
		$("#newPhotoUpload").uploadify({
			"swf": "/x/uploadify/uploadify.swf",
			"uploader": "/x/uploadify/uploadify.php",
			//"buttonText": "+++",	
			'buttonClass': 'uploadButton',
			"cancelImage": "/x/uploadify/uploadify-cancel.png",
			'buttonImage': '/x/images/upload.gif',
			"checkExisting": "/x/uploadify/uploadify-check-exists.php",
			"auto" : true,		
			"fileTypeExts": "*.jpg;*.gif;*.png",
			"fileTypeDesc": "Image files",
			"height": 21,
			"width": 21,
			"removeCompleted": true,
			'removeTimeout': 0,
			'onSelect': function(file) {
				// remove old media file name tr
				$('.newMediaNameTr').remove();
				$('#newMediaSubmit').attr('disabled', true);
			},
			"onUploadSuccess": function(file, data, response){		
				$('#newMediaSubmit').attr('disabled', false);
				var fileName = file.name;
				if (fileName == '')
				{
					$("#newMediaErrorRow").show();
					$("#newMediaErrorMessage").html(fileName);
					$("#newPhotoFilename").val('');	
				}
				else
				{
					$("#newMediaErrorRow").hide();
					$("#newMediaErrorMessage").html("");
					$("#newPhotoFilename").val(fileName);
				}
			},
			'onUploadComplete': function(file) {
				// add new media file name tr
				var fileName = $('#newPhotoFilename').val();
				
				// truncate if file name is too long
				if(fileName.length > 15)
					fileName = fileName.substring(0, 15) + '...';
				$('<tr class="newMediaNameTr">' + '<td></td><td>' + fileName + '</td>' + '</tr>').insertAfter('#newMediaUploadTr').fadeIn();										
			}
		});	
	}
	
	function initNewVideoUpload()
	{
		$("#newVideoUpload").uploadify({
			"swf": "/x/uploadify/uploadify.swf",
			"uploader": "/x/uploadify/uploadify.php",
			//"buttonText": "+++",	
			'buttonClass': 'uploadButton',
			"cancelImage": "/x/uploadify/uploadify-cancel.png",
			'buttonImage': '/x/images/upload.gif',
			"checkExisting": "/x/uploadify/uploadify-check-exists.php",
			"auto" : true,		
			"fileTypeExts": '*.flv;*.f4v;*.f4p;*.f4a;*.f4b;*.aac',
			"fileTypeDesc": 'Video files',
			"height": 21,
			"width": 21,
			"removeCompleted": true,
			'removeTimeout': 0,
			'onSelect': function(file) {
				// remove old media file name tr
				$('.newMediaNameTr').remove();
				$('#newMediaSubmit').attr('disabled', true);
			},
			"onUploadSuccess": function(file, data, response){
				$('#newMediaSubmit').attr('disabled', false);
				var fileName = file.name;
				if (fileName == '')
				{
					$("#newMediaErrorRow").show();
					$("#newMediaErrorMessage").html(fileName);
					$("#newVideoFilename").val('');			
				}
				else
				{
					$("#newMediaErrorRow").hide();
					$("#newMediaErrorMessage").html("");
					$("#newVideoFilename").val(fileName);
				}
			},
			'onUploadComplete': function(file) {
				// add new media file name tr
				var fileName = $('#newVideoFilename').val();
				
				// truncate if file name is too long
				if(fileName.length > 15)
					fileName = fileName.substring(0, 15) + '...';
				$('<tr class="newMediaNameTr">' + '<td></td><td>' + fileName + '</td>' + '</tr>').insertAfter('#newMediaUploadTr').fadeIn();										
			},
			'onUploadError': function(file,errorCode,errorMsg) {
				alert(errorMsg);
			}
		});
	}
	
	function changeMediaUploadType(uploadType)
	{
		if(uploadType == 'photo')
		{
			$('#newPhotoUploadWrapper').show();
			$('#newVideoUploadWrapper').hide();
		} else if(uploadType == 'video') {
			$('#newVideoUploadWrapper').show();
			$('#newPhotoUploadWrapper').hide();
		}
	}
});